package com.mul.lock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping
public class TestController {

    @Autowired
    private RedissonDistributedLocker locker;
    private static int numbers = 3;

    @GetMapping("/lock")
    public String lock(String sno) {
        RLock rLock = locker.lock(sno, 1000);
        if (numbers == 0) {
            System.out.println("卖完了");
            rLock.unlock();
            return "卖完了";
        }
        try {
            Thread.sleep(1000);
            numbers--;
            System.out.println("购买1,剩余：" + numbers);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        rLock.unlock();
        return "购买1";
    }

    @GetMapping("/test")
    public String test() {
        RLock rLock = locker.lock("1");
        locker.unlock(rLock);
        return "ok";
    }
}
